package com.effectiv.gooruda.rest.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import org.springframework.stereotype.Component;

import com.effectiv.gooruda.rest.domain.Permission;
import com.effectiv.gooruda.rest.exception.DuplicateDataException;
import com.effectiv.gooruda.rest.service.api.PermissionService;



@Component
public class PermissionServiceImpl extends PermissionService {

	private final String PERMISSION_COLLECTION_BASE = "t_app_permission_";

	@Autowired
	private MongoTemplate template;

	
	public Permission create(Permission p) {
		Permission permission = findByName(p.getName());
		
		if(permission != null){
			throw new DuplicateDataException("Permission with name " + p.getName() + " already exists.");
		}
		
		String collection = PERMISSION_COLLECTION_BASE
				+ "";
		template.save(p, collection);
		return p;
	}

	
	public Permission findByName(String p) {
		String collection = PERMISSION_COLLECTION_BASE
				+ "";
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is(p));

		Permission permission = template.findOne(query, Permission.class,
				collection);

		return permission;
	}

	public Permission findOne(String id) {
		String collection = PERMISSION_COLLECTION_BASE
				+ "";
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id));

		Permission permission = template.findOne(query, Permission.class,
				collection);

		return permission;
	}

}
